package com.vick.com;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import com.gen.tool.AlertDialog_PG;
import com.gen.tool.SoundPlayer;
import com.ouken.com.R;
import com.ouken.tool.ConnectServer;
import com.ouken.tool.MyApp;
import com.vick.tool.DialogTool;
import com.vick.tool.MiscTool;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class GameoverActivity extends Activity {
	private String word;
	private TextView tv_word;
	private Handler mHandler = new Handler();
	private boolean isAlive;
	private CountDownTimer countDown=new CountDownTimer(5000, 1000) {
		public void onTick(long millisUntilFinished) {
		}

		public void onFinish() {
			new ReadyReturnRoomTask().execute();
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gameover);
		
		isAlive=true;

		/*----- Set word -----*/
		Intent intent = getIntent();
		word = intent.getStringExtra("word");
		tv_word = (TextView) findViewById(R.id.gameoverActivity_tv_word);
		tv_word.setText(word);

		new GetGameRankingTask().execute();
		/*----- Click Add -----*/
		ImageButton ib_add = (ImageButton) findViewById(R.id.gameoverActivity_ib_add);
		ib_add.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				new AddDictTask().execute(word);
			}
		});

	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(checkReturnRoomTask);
		countDown.cancel();
	}


	private class GetGameRankingTask extends AsyncTask<String, Void, String> {
		private AlertDialog_PG progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = DialogTool.showProgressDialog(GameoverActivity.this, "Getting ranking...");
		}

		@Override
		protected String doInBackground(String... params) {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp.getUserEmail()));
			connectParams.add(new BasicNameValuePair("roomname", myApp.getRoomName()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("ParamEnd", "ParamEndParamEndParamEnd"));
			return ConnectServer.connect("http://"+ConnectServer.getServerAdd()+"/game/ranking", connectParams);
		}

		@Override
		protected void onPostExecute(String result) {
			DialogTool.cancelProgressDialog(progressDialog);
			if (!DialogTool.checkNetworkAlive(result,GameoverActivity.this,null)){
				countDown.start();
				return;
			}
			if(!DialogTool.checkLogin(result, GameoverActivity.this))
				return;
			String[] resultParam = result.split(",");
			// OK, Vicky,100,oken,25,genhana,20
			if ("OK".equals(resultParam[0])) {
				int n = (resultParam.length - 1) / 2;
				Player player[] = new Player[n];
				for (int i = 0; i < n; i++) {
					int posName = i * 2 + 1;
					int posScore = i * 2 + 2;
					player[i] = new Player();
					player[i].name = resultParam[posName];
					player[i].score = Integer.parseInt(resultParam[posScore]);
				}
				showRanking(player);
				countDown.start();
			} else {
				DialogTool.showCustomMessage(GameoverActivity.this, result);
			}
		}

		private void showRanking(Player[] player) {
			TextView[] rank = new TextView[5];
			TextView[] name = new TextView[5];
			TextView[] pt = new TextView[5];
			rank[0] = (TextView) findViewById(R.id.gameoverActivity_tv_rank1);
			rank[1] = (TextView) findViewById(R.id.gameoverActivity_tv_rank2);
			rank[2] = (TextView) findViewById(R.id.gameoverActivity_tv_rank3);
			rank[3] = (TextView) findViewById(R.id.gameoverActivity_tv_rank4);
			rank[4] = (TextView) findViewById(R.id.gameoverActivity_tv_rank5);
			name[0] = (TextView) findViewById(R.id.gameoverActivity_tv_name1);
			name[1] = (TextView) findViewById(R.id.gameoverActivity_tv_name2);
			name[2] = (TextView) findViewById(R.id.gameoverActivity_tv_name3);
			name[3] = (TextView) findViewById(R.id.gameoverActivity_tv_name4);
			name[4] = (TextView) findViewById(R.id.gameoverActivity_tv_name5);
			pt[0] = (TextView) findViewById(R.id.gameoverActivity_tv_pt1);
			pt[1] = (TextView) findViewById(R.id.gameoverActivity_tv_pt2);
			pt[2] = (TextView) findViewById(R.id.gameoverActivity_tv_pt3);
			pt[3] = (TextView) findViewById(R.id.gameoverActivity_tv_pt4);
			pt[4] = (TextView) findViewById(R.id.gameoverActivity_tv_pt5);
			int nPlayer = player.length;

			boolean swapped = true;
			/*----- Sort score -----*/
			int j = 0;
			Player tmp;
			while (swapped) {
				swapped = false;
				j++;
				for (int i = 0; i < nPlayer - j; i++) {
					if (player[i].score < player[i + 1].score) {
						tmp = player[i];
						player[i] = player[i + 1];
						player[i + 1] = tmp;
						swapped = true;
					}
				}
			}
			/*----- Display ranking -----*/
			for (j = 0; j < nPlayer; j++) {
				rank[j].setText(Integer.toString(j + 1));
				pt[j].setText(Integer.toString(player[j].score));
				name[j].setText(player[j].name);
			}
			for (; j < 5; j++) {
				rank[j].setText("--");
				name[j].setText("--");
				pt[j].setText("--");
			}
		}
	}

	private class AddDictTask extends AsyncTask<String, Void, String> {
		private AlertDialog_PG progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = DialogTool.showProgressDialog(GameoverActivity.this, "Adding word...");
		}

		@Override
		protected String doInBackground(String... params) {// 0 word
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp.getUserEmail()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("word", params[0]));
			//connectParams.add(new BasicNameValuePair("word", "bazooka"));
			connectParams.add(new BasicNameValuePair("ParamEnd", "ParamEndParamEndParamEnd"));
			return ConnectServer.connect("http://"+ConnectServer.getServerAdd()+"/dict/add", connectParams);
		}

		@Override
		protected void onPostExecute(String result) {
			DialogTool.cancelProgressDialog(progressDialog);
			if (!DialogTool.checkNetworkAlive(result,
					GameoverActivity.this, null))
				return;
			if(!DialogTool.checkLogin(result, GameoverActivity.this))
				return;
			String[] resultParam = result.split(",");

			// if success go to room list
			if(!isAlive)
				return;
			if ("OK".equals(resultParam[0])) {
				DialogTool.showFlashMessage(GameoverActivity.this, "Word Added");
			} else if ("ERROR".equals(resultParam[0]) && "exist".equals(resultParam[1])) {
				DialogTool.showFlashMessage(GameoverActivity.this, "Word already exits");
			} else {
				DialogTool.showCustomMessage(GameoverActivity.this, result);
			}
		}

	}
	private class ReadyReturnRoomTask extends AsyncTask<String, Void, String>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... arg0) {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp.getUserEmail()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("roomname", myApp.getRoomName()));
			connectParams.add(new BasicNameValuePair("ParamEnd", "ParamEndParamEndParamEnd"));
			return ConnectServer.connect("http://"+ConnectServer.getServerAdd()+"/game/waitnext", connectParams);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!DialogTool.checkNetworkAlive(result,
					GameoverActivity.this, null))
				return;
			if(!DialogTool.checkLogin(result, GameoverActivity.this))
				return;
			String[] resultParam = result.split(",");

			if ("OK".equals(resultParam[0])) {
				mHandler.removeCallbacks(checkReturnRoomTask);
				mHandler.post(checkReturnRoomTask);
			} else {
				DialogTool.showCustomMessage(GameoverActivity.this, result);
			}
		}

		
		
	}
	private Runnable checkReturnRoomTask=new Runnable() {
		
		@Override
		public void run() {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp.getUserEmail()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("roomname", myApp.getRoomName()));
			connectParams.add(new BasicNameValuePair("ParamEnd", "ParamEndParamEndParamEnd"));
			String result = ConnectServer.connect("http://"+ConnectServer.getServerAdd()+"/game/checkreturnroom", connectParams);
			
			if (!DialogTool.checkNetworkAlive(result,
					GameoverActivity.this,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							
							mHandler.postDelayed(checkReturnRoomTask, 2000);

						}
					}))
				return;
			if(!DialogTool.checkLogin(result, GameoverActivity.this))
				return;
			String[] resultParam = result.split(",");

			if ("OK".equals(resultParam[0])) {
				if("waiting".equals(resultParam[1])){ // someone not ready, still wait
					mHandler.postDelayed(checkReturnRoomTask, 1000);
				}else{ // everyone ready, return to room
					isAlive=false;
					MiscTool.goToRoom(GameoverActivity.this,null);
					GameoverActivity.this.finish();
				}
			}  else if ("ERROR".equals(resultParam[0]) && "notlogin".equals(resultParam[1])) {
				//DialogTool.showNotLoginDialog(GameoverActivity.this);
				DialogTool.showCustomMessage(GameoverActivity.this, result);
			} else {
				//DialogTool.showNetworkErrorDialog(GameoverActivity.this);
				DialogTool.showCustomMessage(GameoverActivity.this, result);
			}
		}
	};
}
